package org.bpms.service.wechat;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.bpms.model.wechat.WeixinMenu;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.utils.JsonUtils;

/**
 * 微信自定义菜单业务层
 * @author hupei
 *
 */
public class WeixinMenuService {
	
	/**
	 * 保存菜单
	 * @param menu
	 * @return
	 */
	@Before(Tx.class)
	public WeixinMenu saveOrUpdate(WeixinMenu menu){
		if (null != menu.getStr("id")){
			menu.update();
		}else{
			menu.set("id", UUID.randomUUID().toString().replaceAll("-", ""));
			if (null == menu.getStr("pid") || menu.getStr("pid").equals(""))
				menu.set("pid", "-1");
			menu.save();
		}
		return menu;		
	}
	
	/**
	 * 递归删除菜单
	 * @param menu
	 */
	@Before(Tx.class)
	public void delMenu(WeixinMenu menu){
		menu = WeixinMenu.me.findById(menu.getStr("id"));
		if (null != menu){
			List<WeixinMenu> slist = WeixinMenu.me.find("select * from weixinmenu where pid=?" ,
					menu.getStr("id"));
			for (WeixinMenu sm:slist){
				this.delMenu(sm);
			}
			WeixinMenu.me.deleteById(menu.getStr("id"));
		}		
	}
	
	/**
	 * 递归查询所有菜单
	 * @param slist
	 * @param menu
	 */
	public void allMenu(List<WeixinMenu> sl , WeixinMenu menu){
		List<WeixinMenu> slist = null;
		if (null == menu.getStr("id")){
			slist = WeixinMenu.me.find("select * from weixinmenu where  pid='-1' ");
		}else{
			slist = WeixinMenu.me.find("select * from weixinmenu where pid=? " , menu.getStr("id"));
		}
		menu.setLw(slist);
		if (null != menu.getStr("id") && menu.getStr("pid").equals("-1")){//只加入顶层的menu
			sl.add(menu);
		}
		if (null != slist && slist.size() > 0){
			for (WeixinMenu temp : slist){
				this.allMenu(sl , temp);
			}
		}		
	}
	
	/**
	 * 根据所有菜单生成微信菜单的json字符串
	 * @return
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonGenerationException 
	 */
	public String WeixinMenu(String appid) throws JsonGenerationException, JsonMappingException, IOException{
		List<WeixinMenu> slist = null;
		slist = WeixinMenu.me.find("select * from weixinmenu where  pid='-1' ");
		Map<String, Object> map = new HashMap<String , Object>();
		//ObjectMapper mapper = new ObjectMapper();
		if (null != slist && slist.size() > 0){
			List<HashMap> lh = new ArrayList<HashMap>();
			for (WeixinMenu menu:slist){
				HashMap<String, Object> cmap = new HashMap<String , Object>();
				cmap.put("name", menu.getStr("text"));
				cmap.put("type", menu.getStr("type"));
				if (null != menu.getStr("eurl") && !menu.getStr("eurl").equals("")){
					String url = PropKit.use("config.properties").get("domain")+"wechatapi/exturl/"+menu.getStr("id");
					cmap.put("url", SnsAccessTokenApi.getAuthorizeURL(appid, url, true));
				}else{
					if (null != menu.getStr("url") && !menu.getStr("url").equals("")){
						cmap.put("url", SnsAccessTokenApi.getAuthorizeURL(appid, menu.getStr("url"), true));
					}
					if (null != menu.getStr("key") && !menu.getStr("key").equals("")){
						cmap.put("key", menu.getStr("key"));
					}					
				}
				List<WeixinMenu> temp = WeixinMenu.me.find("select * from weixinmenu where  pid=?"
						, menu.get("id"));
				if (null != temp && temp.size() > 0){
					List<HashMap> clh = new ArrayList<HashMap>();
					for (WeixinMenu cmenu:temp){
						HashMap<String, String> ccmap = new HashMap<String , String>();
						ccmap.put("name", cmenu.getStr("text"));
						ccmap.put("type", cmenu.getStr("type"));
						if (null != cmenu.getStr("eurl") && !cmenu.getStr("eurl").equals("")){
							String url = PropKit.use("config.properties").get("domain")+"wechatapi/exturl/"+cmenu.getStr("id");
							ccmap.put("url", SnsAccessTokenApi.getAuthorizeURL(appid, url, true));							
						}else{
							if (null != cmenu.getStr("url") && !cmenu.getStr("url").equals("")){
								ccmap.put("url", SnsAccessTokenApi.getAuthorizeURL(appid, cmenu.getStr("url"), true));
							}
							if (null != cmenu.getStr("key") && !cmenu.getStr("key").equals("")){
								ccmap.put("key", cmenu.getStr("key"));
							}							
						}
						clh.add(ccmap);
					}
					
					if (clh.size() > 0){
						cmap.put("sub_button", clh);
					}
				}
				lh.add(cmap);
			}
			map.put("button", lh);
		}
		return JsonUtils.toJson(map);
		//mapper.writeValueAsString(map);
	}
	
	/**
	 * 保存菜单树
	 * @param maptree
	 */
	@Before(Tx.class)
	public void saveTree(Map maptree){
		if (null != maptree.get("pId")){
			WeixinMenu menu = new WeixinMenu();
			menu.set("pid", maptree.get("pId"))
			           .set("text", (String)maptree.get("text"))
			           .set("type", (String)maptree.get("type"))
			           .set("key", (String)maptree.get("key"))
			           .set("exturl", (String)maptree.get("exturl"))
			           .set("url", (String)maptree.get("url"));
			if (null != maptree.get("id")){
				menu.set("id", maptree.get("id"));
				menu.update();
			}else{
				menu.set("id", UUID.randomUUID().toString().replaceAll("-", ""));
				menu.save();
			}
		}
		if (null != maptree.get("children")){
			List list = (ArrayList) maptree.get("children");
			if (null != list){
				for (int i = 0 ; i < list.size() ; i++){
					Map temp = (Map)list.get(i);
					if (null != temp){
						saveTree(temp);
					}
				}
			}
		}		
	}
	
	/**
	 * 查找微信自定义菜单
	 * @param id
	 * @return
	 */
	public WeixinMenu findById(String id){
		WeixinMenu menu = WeixinMenu.me.findById(id);
		return menu;
	}
}
